'''
Created on Jul 11, 2013

@author: beeaton
'''

import logging, json, httplib, time
import RPi.GPIO as io
io.setmode(io.BCM)

#Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('log')

#Setup PI pin numbers for door sensor
door_pin = 23
#io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP) #activate pi with PullUp resistor

#Setup push connection
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()

# Create installation subscriber
def createParseInstallation():
    connection.request('POST', '/1/installations', json.dumps({
       "deviceType": "android",
       "installationId": "2616cd75-3342-483f-96db-76e4fdd2f901",
       "appName": "Garage Door Sensor-Web",
     }), {
       "X-Parse-Application-Id": "",
       "X-Parse-REST-API-Key": "",
       "Content-Type": "application/json"
     })
    result = json.loads(connection.getresponse().read())
    logger.info(result)


# Create push notification
def pushStatusToDevice(doorPosition):
    connection.request('POST', '/1/push', json.dumps({
       "channels": [
         "GarageDoorStatus"
       ],
       "data": {
         #"alert": "Garage Door Open"
         "alert": "Garage Door " + doorPosition
       }                                         
     }), {
       "X-Parse-Application-Id": "",
       "X-Parse-REST-API-Key": "",
       "Content-Type": "application/json"
     })
    result = json.loads(connection.getresponse().read())
    logger.info(result)

#Create and initialize the parse pusher for the garage door sensor
createParseInstallation()
pushStatusToDevice()
while True:
    if io.input(door_pin):
        logger.info("Door Open")
        pushStatusToDevice("Open")
    time.sleep(0.5)
        

#pushStatusToDevice()